#include<iostream>
#include<string>
#include<time.h>
#include<unistd.h>
#include<assert.h>
#include"Socket.hpp"
#include"Protocol.hpp"

static void Usage(const string& proc)
{
    cout<<"\nUsage:"<<proc<<"Please input server_ip and server_port...\n"<<endl;
}

//./client_clt server_ip server_port
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(0);
    }
    string server_ip=argv[1];//目的主机ip
    uint16_t server_port=stoi(argv[2]);//目的端口号
 
    Sock sockfd;
    sockfd.Socket();//创建客户端套接字
    if(sockfd.Connect(server_ip,server_port)==0)return 1;//向服务器发送连接请求

    srand(time(nullptr));
    int cnt=10;
    string oprs="+-*/%&^";

    string inbuffer_string;//存放那些收到的、不完整的数据
    while(cnt--)
    {
        cout<<"第"<<10-cnt<<"次测试..."<<endl;

        int x=rand()%100;
        usleep(123);
        int y=rand()%100;
        usleep(321);
        char opr=oprs[rand()%oprs.size()];

        Request req(x,y,opr);
        req.DebugPrint(); 
        
        string package;
        req.Serialize(package);
        //cout<<"序列化后的任务,len:"<<package.c_str()<<endl;

        package=Encode(package);
        cout<<"序列化、封装报头后的任务,len:"<<package.c_str()<<endl;

        write(sockfd._sockfd,package.c_str(),package.size());//写到自己的发送缓冲区内

        char buffer[128];
        ssize_t n=read(sockfd._sockfd,buffer,sizeof(buffer)-1);//此处我们仍无法保证读到的是一个完整的报文
        if(n>0)
        {
            buffer[n]='\0';
            inbuffer_string+=buffer;

            string content;
            bool ret=Decode(inbuffer_string,content);//解包
            assert(ret);

            Response rep;
            ret=rep.Deserialize(content);//反序列化
            assert(ret);

            rep.DebugPrint();
        }

        sleep(1);
    }

    sockfd.Close();

    return 0;
}